﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Algorithms
{
    /// <summary>
    /// 字符串转换为整数(atoi)
    /// https://leetcode.com/problems/string-to-integer-atoi/
    /// </summary>
    public class StringToInteger
    {
        //+ 43 - 45 0~9 48~57

        public static int Action2(string str)
        {
            List<char> s = new List<char>();

            str = str.Trim();

            foreach (var t in str)
            {
                if (t == 43 || t == 45)
                {
                    if (s.Count > 0)
                    {
                        break;
                    }
                    else
                    {
                        s.Add(t);
                    }
                }else if (t > 47 && t < 58)
                {
                    s.Add(t);
                }
                else
                {

                    break;
                }
            }

            if (s.Count < 1)
            {
                return 0;
            }

            if (s.Count == 1 && (s[0] == 43 || s[0] == 48 || s[0] == 45))
            {
                return 0;
            }

            long result = 0;
            int j = -1;
            int i = 0;
            if(s[0] == 43 || s[0] == 45)
            {
                i = 1;
            }
            for (; i < s.Count; i++)
            {
                if (  j < 1 && s[i] != 48)
                {
                    j = i;
                }

                if (j > -1)
                {
                    result += (long)((s[i] - 48) * Math.Pow(10, s.Count - i - 1));
                    if ((s[0] == 43 || s[0] > 45) && (result >= int.MaxValue|| s.Count-j>10))
                    {
                        return int.MaxValue;
                    }
                    else if (s[0] == 45 && (result - 1 >= int.MaxValue|| s.Count - j > 10))
                    {
                        return int.MinValue;
                    }
                }
            }

            result= s[0] == 45 ? result * -1:
            result;
            return (int)result;

        }


    }
}
